package com.fang.java.ctrl;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController {
	
	private Log log = LogFactory.getLog(IndexController.class);

	@RequestMapping(value={"","index"})
	public String index(){
		return "index";
	}
	@RequestMapping(value = "/weixin/receiveServlet.jhtml", method = { RequestMethod.GET, RequestMethod.POST })
	public void receiveServlet(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
		log.info("--------------------------微信推送返回信息-----------------");
		 	log.info(request.getQueryString());
		 	log.info("--------------------------微信推送返回信息---------/--------");
		    ServletInputStream inputStream = request.getInputStream();
	        ServletOutputStream outputStream = response.getOutputStream();
	        String signature = request.getParameter("signature");
	        String timestamp = request.getParameter("timestamp");
	        String nonce = request.getParameter("nonce");
	        String echostr = request.getParameter("echostr");

	        //加密模式
	        String encrypt_type = request.getParameter("encrypt_type");
	        String msg_signature = request.getParameter("msg_signature");
			
	    	wxBizMsgCrypt wxBizMsgCrypt = null;
	    	//加密方式
	    	boolean isAes = "aes".equals(encrypt_type);
	    	if(isAes){
	    		try {
					wxBizMsgCrypt = new WXBizMsgCrypt(encodingToken, encodingAesKey, appId);
					log.info("wx wxBizMsgCrypt="+wxBizMsgCrypt); 
					log.info("token="+encodingToken); 
				} catch (AesException e) {
					e.printStackTrace();
				}
	    	}

	        //首次请求申请验证,返回echostr
	        if(isAes&&echostr!=null){
	        	try {
					echostr = URLDecoder.decode(echostr,"utf-8");
					String echostr_decrypt = wxBizMsgCrypt.verifyUrl(msg_signature, timestamp, nonce, echostr);
					outputStreamWrite(outputStream,echostr_decrypt);
					return;
				} catch (AesException e) {
					e.printStackTrace();
				}
	        }else if(echostr!=null){
	            outputStreamWrite(outputStream,echostr);
	            return;
	        }

	        EventMessage eventMessage = null;
	        if(isAes){
	        	try {
					//获取XML数据（含加密参数）
					String postData = StreamUtils.copyToString(inputStream, Charset.forName("utf-8"));
					//解密XML 数据
					String xmlData = wxBizMsgCrypt.decryptMsg(msg_signature, timestamp, nonce, postData);
					 log.info("\n-------xmlData--------\n");
						log.info("wx xmlData="+xmlData); 
						log.info("\n---------------\n");
						
					//XML 转换为bean 对象
					eventMessage = XMLConverUtil.convertToObject(EventMessage.class, xmlData);
					//接收失败
					if(eventMessage == null){
						System.err.println("----------------------消息接收不到,进行重排1--------------");
						RespUtil.renderXml(response, "");
						return ;
					}
				} catch (AesException e) {
					e.printStackTrace();
				}
	        }else{
	        	try{
	        		   //验证请求签名
			        if(!signature.equals(SignatureUtil.generateEventMessageSignature(token,timestamp,nonce))){
			            return;
			        }
	        	}catch(Exception e){
	        		
	        	}
		     

		        if(inputStream!=null){
		        	/*Scanner scanner = new Scanner(inputStream,"utf-8");
		        	while(scanner.hasNext()){
		        		log.info("----$$-----"+scanner.nextLine());
		        	}
		        	scanner.close();*/
		        	//XML 转换为bean 对象
		        	String postData = StreamUtils.copyToString(inputStream, Charset.forName("utf-8"));
		        	log.info("----发送的消息----"+postData); 
		            eventMessage = XMLConverUtil.convertToObject(EventMessage.class,postData);
		            //接收失败
					if(eventMessage == null){
						System.err.println("----------------------消息接收不到,进行重排2--------------");
						return ;
					}
		            String openid = eventMessage.getFromUserName();
		            String msgType = eventMessage.getMsgType();
		            String event = eventMessage.getEvent(); // subscribe 
		            String eventKey = eventMessage.getEventKey(); // qrscene qrscene_f3,32,32
		            
		            String qrcodeId = null;
		            
		            log.info("send user openid="+openid); 
		            this.setOpenid(request.getSession(), openid);
		            
		        	UserBind userBind = userBindService.getByOpenid(openid);
		        	
		        	log.info("userBind="+userBind);
		        	  
//	            	if(userBind==null){
//	            		userBind = new UserBind();
//	            		userBind.setPlatform("WEIXIN");
//	            		userBind.setOpenid(openid);
//						
//						this.userBindService.update(userBind);
//						
//						Channel channel = null ;
//	            		String ticketId = null;
//	            		
//						WeiXinUser wxuser = getWeixinUser(openid);
//						if(wxuser != null){ 
//							RbacUser rbacUser =	this.registerWeiXinUser(wxuser, openid,channel,ticketId); 
//							userBind.setRbacUser(rbacUser);
//							this.userBindService.update(userBind);
//						}
//						 
//	            	}else{
//
//						Channel channel = null ;
//	            		String ticketId = null;
//						WeiXinUser wxuser = getWeixinUser(openid);
//						if(wxuser != null){ 
//							RbacUser rbacUser = this.registerWeiXinUser(wxuser, openid,channel,ticketId); 
//							userBind.setRbacUser(rbacUser);
//							this.userBindService.update(userBind);
//						}
//	            	}
	            	
		            log.info("wx getMsgType="+eventMessage.getMsgType()); 
		            log.info("wx toUserName="+eventMessage.getToUserName()); 
		            log.info("wx FromUserName="+eventMessage.getFromUserName()); 
		            log.info("wx getEvent="+eventMessage.getEvent()); 
		            log.info("wx getEventKey="+eventMessage.getEventKey()); 
		            log.info("wx getContent="+eventMessage.getContent()); 
		            
		            log.info("wx getLatitude="+eventMessage.getLatitude()); 
		            log.info("wx getLongitude="+eventMessage.getLongitude()); 
		            
		            log.info("wx getDescription="+eventMessage.getDescription()); 
		            log.info("wx CardId="+eventMessage.getCardId()); 
		            log.info("wx CodeId="+eventMessage.getCodeId()); 
		            if(StringUtil.isNotBlank(event) && event.equalsIgnoreCase("subscribe")){
		            	if(eventKey!=null){
		            		qrcodeId = eventKey.replaceFirst("qrscene_", "");
		            		
		            	}
		            	
		            
		            }
		            
		            if(StringUtil.isNotBlank(event) && event.equalsIgnoreCase("SCAN")){
		            	qrcodeId = eventKey;
		            	
		            }
		            String openId = eventMessage.getFromUserName();
		            RbacUser user = userBindService.getByWeiXinOpenid(openId);
		            
		            //领取卡券推送  fang 20160726
		            if(StringUtil.isNotBlank(event) && event.equalsIgnoreCase("user_get_card")){
		            	
		            	log.info("---------------进入卡券领取推送----------------");
		            	String cardId = eventMessage.getCardId();
		            	String codeId = eventMessage.getCodeId();
		            	log.info("---------------openId----------------"+openId);
		            	log.info("---------------cardId----------------"+cardId);
		            	log.info("---------------codeId- ---------------"+codeId);
		            	
		            	TicketRules ticketRules = ticketRulesService.findOne("from TicketRules where cardId=?", new Object[]{cardId});
		            	String channleId = ticketRules.getLimit_channel();
		            	Channel channel = null;
		            	if(channleId.indexOf(",")!=-1){
		            		channleId = channleId.split(",")[0];
		            	}
		            	if(channleId!=null){
		            		channel = channelService.findOne(channleId);
		            	}
		            	if(ticketRules!=null){
		            		if(user==null){
		            			WeiXinUser wxuser = getWeixinUser(openid);
		            			user = registerWeiXinUser(wxuser, openId, channel, ticketRules.getId());
			            	}
		            		UserTicket userTicket = haveTicket(user,ticketRules.getId());
		            		userTicket.setCode(codeId);
		            		userTicketService.update(userTicket);
		            	}
		            	log.info("---------------完成卡券领取推送----------------");
		            	
		            }
		            
		            
		            //扫码
		            if(StringUtil.isNotBlank(qrcodeId)){
		            	WeiXinQrcode weixinQrcode = this.weixinQrcodeService.findOne(qrcodeId);
		            	if(weixinQrcode != null){
		            		Channel channel = null ;
		            		String channelId = null;
		            		String ticketId = null;
		            		
		            		channelId = weixinQrcode.getChannelId();
							ticketId = weixinQrcode.getTicketId();

							if(StringUtil.isNotBlank(channelId)){
								channel = this.channelService.findOne(channelId);
							}
							
							if(user==null){
		            			WeiXinUser wxuser = getWeixinUser(openid);
		            			user = registerWeiXinUser(wxuser, openId, channel,ticketId);
		            			userBind = userBindService.getByOpenid(openid);
			            	}
							
//							
//		            		userBind.setOpenid(openid);
//		            		
//		            		userBind.setChannelId(weixinQrcode.getChannelId());
//							userBind.setTicketId(weixinQrcode.getTicketId());
							
							
							//userBind = this.userBindService.update(userBind); 
			            	
							RbacUser rbacUser = null;
							//edit by fang 20160809用户渠道添加错误bug修复
							channelId = weixinQrcode.getChannelId();
							ticketId = weixinQrcode.getTicketId();
							TicketRules ticketRules = ticketRulesService.findOne(ticketId);
							if(ticketRules!=null){
								channelId = ticketRules.getLimit_channel();
								if(channelId.indexOf(",")!=-1){
									channelId = channelId.split(",")[0];
								}
							}
			            	if(userBind.getRbacUser() == null){
			            		//绑定账号
								if(StringUtil.isNotBlank(channelId)){
									channel = this.channelService.findOne(channelId);
								}
								WeiXinUser wxuser = getWeixinUser(openid);
								if(wxuser != null){ 
									rbacUser = this.registerWeiXinUser(wxuser, openid,channel,ticketId); 
									userBind.setRbacUser(rbacUser);
									this.userBindService.update(userBind);
								}
			            	}else {
			            		rbacUser = userBind.getRbacUser();
			            		
								if(StringUtil.isNotBlank(channelId)){
									rbacUser.setChannel(channelId);
								}
								if(StringUtil.isNotBlank(ticketId)){
									rbacUser.setTicketId(ticketId);
								}
								
								if(StringUtil.isNotBlank(channelId)){
									channel = this.channelService.findOne(channelId);
								}
								
								if(channel != null){
									rbacUser.setChannelName(channel.getName());
								}
			            		
								this.userService.update(rbacUser);
								
			            	}
			            	
			            	//自动发放优惠券
			            	haveTicket(rbacUser,ticketId);
		            	}
		            	 
		            }
		            //end 扫码
		           /* //编码message fang 20160413
		            if(eventMessage!= null && eventMessage.getContent() != null){
		            	eventMessage.setContent(new String(eventMessage.getContent().getBytes("gbk"),"utf-8"));
		            }*/
		            
		            if(StringUtil.isNotBlank(event) && event.equalsIgnoreCase("subscribe")){
		            	List<Filter> filters = new ArrayList<Filter>();
		            	filters.add(Filter.eq("enabled", true));
		            	filters.add(Filter.eq("subscribe", true));
		            	List<KeywordFeed> keywordFeedList = keywordFeedService.findList(filters);
		            	if(keywordFeedList.size()<=0){
		            		/*String content = "BEFORE\n\n"+
									"在“康吸来了”问世之前\n\n"+
									"呼吸，这个严肃的问题\n\n"+
									"从来没有被\n\n"+
									"“走心走肾”地解决过\n\n"+
									"DON’T  WORRY\n\n"+
									"康吸来了，让呼吸更纯粹～\n\n";*/
//			    			//创建回复
			    			XMLTextMessage xmlTextMessage = new XMLTextMessage(
			    			     eventMessage.getFromUserName(),
			    			     eventMessage.getToUserName(),
			    			     dictionaryCodeValueService.getValueByCode("WEIXIN_CONFIG", "WEIXIN_WELCOME"));
			    			//回复
			    			xmlTextMessage.outputStreamWrite(outputStream,wxBizMsgCrypt);
			    			
		            		/*String mediaId = ConfigUtil.getConfig("WEL_IMG");
			    			XMLImageMessage xmlImageMessage = new XMLImageMessage( eventMessage.getFromUserName(),eventMessage.getToUserName(), mediaId);
			    			xmlImageMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);*/
			    			
		            	}else{
		            		
		            		// 1文本 text 2 图片 image 3 新闻 news
		            		KeywordFeed feed = keywordFeedList.get(0);
		            		if(feed.getFeedType() == 1){
		            			String content = feed.getContent();
		            			
		            			XMLTextMessage xmlTextMessage = new XMLTextMessage(
					    			     eventMessage.getFromUserName(),
					    			     eventMessage.getToUserName(),
					    			     content);
					    			//回复
					    			xmlTextMessage.outputStreamWrite(outputStream,wxBizMsgCrypt);
		            		}else if(feed.getFeedType() == 2){
		            			
		            		}else if(feed.getFeedType() == 3){
		            			 
		            		}
		            	}
		            }
		            
		            if(StringUtil.isNotBlank(msgType) && msgType.equalsIgnoreCase("text")){
		            	//口令操作 0601 fang 增加优惠券口令获取
		            	//以口令第一个字母区分口令所对应的活动,若口令是非字母开头,则该口令是红包领取口令
		            	String contentCommand = eventMessage.getContent().trim();
		            	if(contentCommand.matches("[a-zA-z](\\d)+")){//若是以字母开头则是优惠券指令活动
		            		Pattern r = Pattern.compile("\\d+");
		            		String[] strs = r.split(contentCommand);
		            		String headStr =  strs[0];//首字母
		            		List<Filter> fList = new ArrayList<Filter>();
		            		fList.add(Filter.eq("headTag", headStr));
		            		fList.add(Filter.le("startDate", new Date()));
		            		fList.add(Filter.ge("dieDate",  new Date()));
		            		List<TicketActivity> list = ticketActivityService.findList(fList);
		            		if(list != null && list.size() > 0){
		            			TicketActivity ticketActivity = list.get(0);
		            			List<Filter> fList2 = new ArrayList<Filter>();
		            			fList2.add(Filter.eq("ticketActivity", ticketActivity));
		            			fList2.add(Filter.eq("name", contentCommand, true));
		            			List<TicketCommand> ticketCommands = ticketCommandService.findList(fList2);
		            			if(ticketCommands != null && ticketCommands.size() > 0){
		            				TicketCommand ticketCommand = ticketCommands.get(0);
		            				if(ticketCommand.getIsUsed()){
		            					//优惠券指令已被使用
		            					sendMsg("领取消息","优惠券指令已被使用。",openid);
		            				}else{
		            					//发放优惠券
		    			            	haveTicket(userBind.getRbacUser(),ticketActivity.getTicketRules().getId());
		    			            	ticketCommand.setIsUsed(true);
		    			            	ticketCommand.setGainner(userBind.getRbacUser());
		    			            	ticketCommandService.update(ticketCommand);
		            				}
		            			}else{
		            				//优惠券指令不存在
		            				sendMsg("领取消息","优惠券指令不正确。",openid);
		            			}
		            		}else{
		            			//优惠券指令不存在
	            				sendMsg("领取消息","优惠券指令不正确。",openid);
		            		}
		            	}else{
		            		//红包领取口令
			            	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
			            	Map<String, Object> result =  laysCommandService.getLaysActivityByCommand(eventMessage.getContent());
			            	if(result != null){
			            		Date startDate = (Date) result.get("start_date");
			            		Date dieDate = (Date) result.get("die_date");
			            		Boolean isUsed = (Boolean) result.get("is_used");
			            		Date nowDate = new Date();
			            		if(nowDate.after(startDate) && nowDate.before(dieDate)){
			            			LaysCommand laysCommand = laysCommandService.findOne((String) result.get("command_id"));
			            			if(!laysActivityService.hasGain(laysCommand.getLaysActivity().getId(),userBind.getRbacUser().getId()) && laysCommand != null){
			            				if(!isUsed && laysCommand != null){
				            				//更新数据库
				            				laysCommand.setGainner(userBind.getRbacUser());
					        	        	laysCommand.setIsUsed(true);
					        	        	laysCommandService.update(laysCommand);	
				            				//发送红包
				            				int total_amount = (Integer) result.get("cash_amout") * 100;
				            				if("1".equals(result.get("cash_type").toString())){//随机金额
				            					int cash_max_amout = (Integer) result.get("cash_max_amout") *100;
				            					total_amount = (int) ((Math.random() * (cash_max_amout - total_amount)) + total_amount);
				            				}
				            				
						            		String nonceStr = UUID.randomUUID().toString().replace("-", "") ;
						            		String mchBillno =  ConfigData.getMch_id()+sdf2.format(new Date())+UUID.randomUUID().toString().replace("-", "").substring(0, 10);
						        			WechatRedPackRequest wechatRedPackRequest = new WechatRedPackRequest();
						        			wechatRedPackRequest.setMch_billno(mchBillno);
						        			wechatRedPackRequest.setWxappid(ConfigData.getAPP_ID());
						        			wechatRedPackRequest.setNonce_str(nonceStr);
						        			wechatRedPackRequest.setMch_id(ConfigData.getMch_id());
						        			wechatRedPackRequest.setMch_billno(mchBillno);
						        			wechatRedPackRequest.setSend_name( ConfigUtil.getConfig("WEIXIN_APP_NAME"));
						        			wechatRedPackRequest.setRe_openid(openid);
						        			wechatRedPackRequest.setTotal_amount(total_amount);
						        			wechatRedPackRequest.setTotal_num(1);
						        			wechatRedPackRequest.setWishing(result.get("wishing").toString());
						        			wechatRedPackRequest.setClient_ip( ReqUtil.getIpAddr(request));
						        			wechatRedPackRequest.setAct_name(result.get("name").toString());
						        			wechatRedPackRequest.setRemark("备注");
						        			String sign = "";
						        	        try {
						        	            sign = WechatUtils.buildRequestSign(wechatRedPackRequest, ConfigData.getKey());
						        	        } catch (Exception e) {
						        	            e.printStackTrace();
						        	        }
						        			wechatRedPackRequest.setSign(sign);
						        			
						        			
						        			FileInputStream instream = null;
						        			try {
						        				System.err.println("-----------start-----------------");
						        				instream = new FileInputStream(new File(request.getSession().getServletContext().getRealPath("/")+ConfigData.getKey_path()));
						        				String resp = HttpUtil.wechatPost(ConfigData.getLays_url(),
							        	                WechatUtils.convertObjectToXml(wechatRedPackRequest, WechatRedPackRequest.class), instream);
							        	        WechatRedPackResponse wechatRedPackResponse = WechatUtils.convertXmlToResponse(resp);

							        	        if (!wechatRedPackResponse.getReturn_code().equals("SUCCESS")) {
							        	            System.err.println(wechatRedPackResponse.getReturn_msg());
							        	        }
							        	        if (!wechatRedPackResponse.getResult_code().equals("SUCCESS")) {
							        	            System.err.println(wechatRedPackResponse.getErr_code() + wechatRedPackResponse.getErr_code_des());
							        	        }
							        	        System.err.println("----result ---"+wechatRedPackResponse.getResult_code());
							        	        if("".equals(wechatRedPackResponse.getResult_code())){
							        	        	//更新数据库
							        	        	laysCommand.setIsUsed(true);
							        	        	laysCommandService.update(laysCommand);				        	        
							        	        }
							        	        System.err.println("-----------end-----------------");
											} catch (Exception e) {
												e.printStackTrace();
											}
				            			}else{
				            				//推送红包已被使用消息
				            				sendMsg("领取消息","红包已被领取。",openid);
				            			}
			            			}else{
			            				//推送红包只能被领取一次
			            				sendMsg("领取消息","同一用户只能领取一次。",openid);
			            			}
			            			
			            		}else{
			            			//推送红包活动过期消息
			            			sendMsg("领取消息","红包领取活动已过期。",openid);
			            		}
			            	}else{
			            		//存储用户聊天消息  20160413
			            		log.info("----messge-88----"+eventMessage.getContent());
			            		Contact contact = new Contact();
			            		BeanUtils.copyProperties(contact, eventMessage);
			            		contact.setCreateTime(new Date());
			            		contact.setWxCreateTime(eventMessage.getCreateTime());
			            		contact =contactService.update(contact);
			            		
			            		//存储聊天记录提示信息
			            		AddTips addTips = new AddTips();
			            		addTips.setAddType(AddType.msg);
			            		addTips.setRefId(contact.getId());
			            		addTipsService.update(addTips);
			            		System.err.println("----update-----------"+eventMessage.toString());
			            	}
		            	}
		            	
		            	
		            	String feedKey = eventMessage.getContent();
		            	log.info("---开始自动回复---");
		            	if(StringUtil.isNotBlank(feedKey)){
		            		log.info("--开始自动回复---"+feedKey);
		            		List<Filter> filters = new ArrayList<Filter>();
		            		filters.add(Filter.eq("enabled", true)); 
			            	filters.add(Filter.eq("subscribe", false));
			            	filters.add(Filter.like("feedKey", "%"+feedKey.trim()+"%"));
			            	List<KeywordFeed> keywordFeedList = keywordFeedService.findList(filters);
		            		
			            	if(keywordFeedList.size()>0){
			            		
			            		Random rand = new Random(); 
				    			int randNum= rand.nextInt(keywordFeedList.size());
				    			
				    			KeywordFeed feed = keywordFeedList.get(randNum);
				    			
				    			if(!feed.getIsWeixin()){//自定义回复  fang 20160715
				    				log.info("--回复类型 聊天类型回复  ---"+feed.getFeedType());
				    				TextMessage message = new TextMessage(userBind.getOpenid(),"<a href='"+feed.getUrl()+"'>"+feed.getContent()+"</a>");
				    				String access_token = TokenManager.getDefaultToken();
				    				BaseResult resutl =  MessageAPI.messageCustomSend(access_token, message);
				    				log.info("--返回内容  ---"+resutl.getErrcode()+resutl.getErrmsg());
				    				
				    			}else{
				    				// 1文本 text 2 图片 image 3 新闻 news
					    			log.info("--回复类型 ---"+feed.getFeedType());
				            		if(feed.getFeedType() == 1){
				            			String content = feed.getContent();
				            			
				            			XMLTextMessage xmlTextMessage = new XMLTextMessage(
							    			     eventMessage.getFromUserName(),
							    			     eventMessage.getToUserName(),
							    			     content);
							    			//回复
							    			xmlTextMessage.outputStreamWrite(outputStream,wxBizMsgCrypt);
				            		}else if(feed.getFeedType() == 2){
				            			String mediaId = feed.getImage();
				            			XMLImageMessage xml =new XMLImageMessage(eventMessage.getFromUserName(),eventMessage.getToUserName(),mediaId);
				            			xml.outputStreamWrite(outputStream,wxBizMsgCrypt);
				            		}else if(feed.getFeedType() == 3){ 
				            			
				            			if(StringUtil.isNotBlank(feed.getMediaId())){
				            				String access_token = TokenManager.getDefaultToken();
					            			
					            			NewsItem itm = MaterialAPI.materialGet_material_newsItem( access_token,feed.getMediaId());
					            			if(itm != null && itm.getNews_item()!=null && itm.getNews_item().size()>0){
					            				for(weixin.popular.bean.Article art : itm.getNews_item()){

							        				List<Article> articles = new ArrayList<Article>();
							        				Article article = new Article();
							        				article.setTitle(art.getTitle());
							        				article.setDescription(art.getDigest());
							        				article.setUrl(art.getContent_source_url());
							        				log.info("--链接 ---"+art.getContent_source_url());
							        				//article.setPicurl(digest);
							        				String thumb_media_id = art.getThumb_media_id();
							        				
							        				String image = feed.getImage();
							        				
							        				if(StringUtil.isBlank(image)){
							        					// thumb_media_id
								        				byte[] imagebytes  = MaterialAPI.materialGet_material(access_token, thumb_media_id);
								        				String filetype = "jpg";
								        				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
								        				
								        				String uploadHeadStr = "/upload/"+ sdf.format(new Date());
								        				File uploadFile = new File(request.getSession().getServletContext().getRealPath(uploadHeadStr));
								        				if (!uploadFile.exists()) {
								        					uploadFile.mkdir();
								        				}
								        		        UUID uuid = UUID.randomUUID();
								        				String fileName = "weixin."+filetype;
								        				String tpath = "/"+uuid+fileName.substring(fileName.lastIndexOf("."));
								        				String path = uploadFile + tpath;
								        		         
								        				FileOutputStream out = new FileOutputStream(path);
								        				try {
								        					out.write(imagebytes);
								        					image = uploadHeadStr + tpath;
								        					
								        					feed.setImage(image);
								        					this.keywordFeedService.update(feed);
								        					
								        				} catch (Exception e) {
								        					e.printStackTrace();
								        				} finally {
								        					out.close();
								        				}
							        				}
							        			
							        				image = ConfigUtil.getConfig("WEIXIN_HOST")+image;
							        				
							        				article.setPicurl(image);
							        				
							        				articles.add(article);
							        				
							            			XMLNewsMessage newsmsg = new XMLNewsMessage(eventMessage.getFromUserName(),
										    			     eventMessage.getToUserName(),articles);
							            			 
							            			newsmsg.outputStreamWrite(outputStream,wxBizMsgCrypt);
					            				}
					            			}
				            			}
				            			
				            		 
				        				
				            		} 
				    			}
				    			
			            	}
			            	
		            	}
		            }
		        }
	        }

	        String expireKey = eventMessage.getFromUserName() + "__"
					   + eventMessage.getToUserName() + "__"
					   + eventMessage.getMsgId() + "__"
					   + eventMessage.getCreateTime();
			if(expireSet.contains(expireKey)){
				//重复通知不作处理
				return;
			}else{
				expireSet.add(expireKey);
			}


	}
	
}
